package cn.edu.swu.miniwebsvr.handler;

import cn.edu.swu.miniwebsvr.core.Handler;
import cn.edu.swu.miniwebsvr.core.Parameter;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class EchoHandler implements Handler {

    @Override
    public void handle(Parameter request, OutputStream response) {
        PrintWriter writer = new PrintWriter(response);

        try {
            Map<String, String> params = request.getAllParams();
            Map<String, String> headers = request.getHeaders();
            Map<String, String> urlParams = request.getUrlParams();
            Map<String, String> bodyParams = request.getBodyParams();

            // 生成纯文本内容
            String plainContent = generatePlainTextContent(request, params, headers, urlParams, bodyParams);
            byte[] contentBytes = plainContent.getBytes(StandardCharsets.UTF_8);

            // 构造完整的 HTTP 响应头
            writer.println("HTTP/1.1 200 OK");
            writer.println("Content-Type: text/plain; charset=UTF-8");
            writer.println("Content-Length: " + contentBytes.length);
            writer.println("Connection: close");
            writer.println("Server: MiniWebSvr/1.0");
            writer.println("Cache-Control: no-cache");
            writer.println(); // 空行分隔头部和正文

            // 写入响应体
            writer.print(plainContent);
            writer.flush();

            System.out.println("EchoHandler: 成功处理回显请求，参数数量: " + params.size());

        } catch (Exception e) {
            System.err.println("EchoHandler处理异常: " + e.getMessage());
            sendErrorResponse(writer, "回显处理器内部错误");
        }
    }

    /**
     * 生成纯文本内容
     */
    private String generatePlainTextContent(Parameter request, Map<String, String> allParams,
                                            Map<String, String> headers, Map<String, String> urlParams,
                                            Map<String, String> bodyParams) {
        StringBuilder content = new StringBuilder();

        content.append("MiniWebSvr Echo Server Response\n");
        content.append("================================\n\n");

        // 请求基本信息部分
        content.append("=== 请求基本信息 ===\n");
        content.append("请求方法: ").append(request.getMethod()).append("\n");
        content.append("请求URL: ").append(request.getUrl()).append("\n");
        content.append("总参数数量: ").append(allParams.size()).append("\n");
        content.append("URL参数数量: ").append(urlParams.size()).append("\n");
        content.append("Body参数数量: ").append(bodyParams.size()).append("\n\n");

        // 所有参数部分
        content.append("=== 所有参数 ===\n");
        if (allParams.isEmpty()) {
            content.append("未接收到任何参数\n");
        } else {
            for (Map.Entry<String, String> entry : allParams.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                String source = urlParams.containsKey(key) ?
                        (bodyParams.containsKey(key) ? "URL & Body" : "URL") : "Body";

                content.append("参数名: ").append(key)
                        .append(" | 参数值: ").append(value)
                        .append(" | 来源: ").append(source)
                        .append("\n");
            }
        }
        content.append("\n");

        // 请求头部分
        content.append("=== 请求头信息 ===\n");
        if (headers.isEmpty()) {
            content.append("未接收到任何请求头\n");
        } else {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                content.append("Header名称: ").append(entry.getKey())
                        .append(" | Header值: ").append(entry.getValue())
                        .append("\n");
            }
        }
        content.append("\n");

        // 使用说明部分
        content.append("=== 使用说明 ===\n");
        content.append("GET请求测试: /echo?param1=value1&param2=value2\n");
        content.append("POST请求测试: 使用表单或API工具发送POST请求到/echo\n");
        content.append("Content-Type: application/x-www-form-urlencoded\n\n");

        content.append("=== 导航 ===\n");
        content.append("返回首页: /\n");
        content.append("查看服务器时间: /time\n");
        content.append("清空参数: /echo?clear=1\n");

        return content.toString();
    }

    /**
     * 发送错误响应
     */
    private void sendErrorResponse(PrintWriter writer, String message) {
        try {
            String errorContent = "Echo Service Error\n" + message;
            byte[] errorBytes = errorContent.getBytes(StandardCharsets.UTF_8);

            writer.println("HTTP/1.1 500 Internal Server Error");
            writer.println("Content-Type: text/plain; charset=UTF-8");
            writer.println("Content-Length: " + errorBytes.length);
            writer.println("Connection: close");
            writer.println();
            writer.print(errorContent);
            writer.flush();
        } catch (Exception e) {
            System.err.println("发送错误响应失败: " + e.getMessage());
        }
    }
}